package com.crawler.gmail.crawler;

import com.crawler.gmail.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.MessagingException;
import javax.mail.Store;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <描述>
 * <详细介绍>
 *
 * @author 王明明
 * @since wiki
 */
public class FetchAllEmail implements Runnable {
    private final static Logger LOGGER = LoggerFactory.getLogger(EmailCrawler.class);


    @Override
    public void run() {
        System.out.println("run .... ");
        // 通过接口 请求所有的 gmail 邮箱配置

        List<EmailFetchSettingDO> arrs = RecruitmentHttpTools.getAllEmailSetting();
        ExecutorService pool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < arrs.size(); i++) {
            int finalI = i;
            System.out.println(JsonUtil.toJson(arrs.get(i)));
            pool.execute(()-> {
                EmailFetchSettingDO emailFetchSettingDO = arrs.get(finalI);;
//                emailFetchSettingDO.setHost("imap.exmail.qq.com");
//                emailFetchSettingDO.setPort(993);
//                emailFetchSettingDO.setSsl(true);
//                emailFetchSettingDO.setPassword("Lucky920106");
//                emailFetchSettingDO.setUsername("shidehong_jianli@qijiayoudao.com");
//                emailFetchSettingDO.setProtocol(1);
//                emailFetchSettingDO.setLastFetchTime(1635782400000L);
                LOGGER.info("开始抓取邮件 {}", emailFetchSettingDO.getUsername());
                EmailCrawler emailCrawler = new EmailCrawler(emailFetchSettingDO);
                try {
                    Store store = emailCrawler.getJavaMailInstance(emailFetchSettingDO);
                    emailCrawler.fetchAllEmail(store);
                    LOGGER.info("邮件抓取完成 {}", emailFetchSettingDO.getUsername());
                } catch (MessagingException | InterruptedException e) {
                    LOGGER.error("邮件抓取出错 " + emailFetchSettingDO.getUsername(), e);
                }
            });
        }

    }
}
